#include "ExecHiddenMSW.h"

#ifdef __WXMSW__
#include <wx/wxprec.h>

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#ifndef WX_PRECOMP
    #include <wx/utils.h>
    #include <wx/app.h>
    #include <wx/intl.h>
    #include <wx/log.h>
    #include <wx/module.h>
#endif

#include <wx/process.h>

#include <wx/apptrait.h>


#include <wx/msw/private.h>

#include <ctype.h>

#if !defined(__GNUWIN32__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
    #include <direct.h>
#ifndef __MWERKS__
    #include <dos.h>
#endif
#endif

#if defined(__GNUWIN32__)
    #include <sys/unistd.h>
    #include <sys/stat.h>
#endif

#if !defined(__WXMICROWIN__) && !defined(__WXWINCE__)
    #ifndef __UNIX__
        #include <io.h>
    #endif

    #ifndef __GNUWIN32__
        #include <shellapi.h>
    #endif
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef __WATCOMC__
    #if !(defined(_MSC_VER) && (_MSC_VER > 800))
        #include <errno.h>
    #endif
#endif
#include <stdarg.h>

#define wxWM_PROC_TERMINATED (WM_USER + 10000)


extern "C" WXDLLIMPEXP_BASE HWND
wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc);

static const wxChar *wxMSWEXEC_WNDCLASSNAME2 = wxT("_wxExecute_Internal_Class2");
static const wxChar *gs_classForHiddenWindow2 = NULL;


// structure describing the process we're being waiting for
struct wxExecuteData2
{
public:
    ~wxExecuteData2()
    {
        if ( !::CloseHandle(hProcess) )
        {
            wxLogLastError(wxT("CloseHandle(hProcess)"));
        }
    }

    HWND       hWnd;         
    HANDLE     hProcess;     
    DWORD      dwProcessId;  
    wxProcess *handler;
    DWORD      dwExitCode;   
    bool       state;        
};

LRESULT APIENTRY _EXPORT wxExecuteWindowCbk2(HWND hWnd, UINT message,
                                            WPARAM wParam, LPARAM lParam) {
    if ( message == wxWM_PROC_TERMINATED )
    {
        DestroyWindow(hWnd);   

        wxExecuteData2 * const data = (wxExecuteData2 *)lParam;
        if ( data->handler )
        {
            data->handler->OnTerminate((int)data->dwProcessId,
                                       (int)data->dwExitCode);
        }

        if ( data->state )
        {
           
           
            data->state = 0;
        }
        else
        {
           
            delete data;
        }

        return 0;
    }
    else
    {
        return ::DefWindowProc(hWnd, message, wParam, lParam);
    }
}


// thread function for the thread monitoring the process termination
static DWORD __stdcall wxExecuteThread2(void *arg) {
    wxExecuteData2 * const data = (wxExecuteData2 *)arg;

    if ( ::WaitForSingleObject(data->hProcess, INFINITE) != WAIT_OBJECT_0 )
    {
        wxLogDebug(_T("Waiting for the process termination failed!"));
    }

   
    if ( !::GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
    {
        wxLogLastError(wxT("GetExitCodeProcess"));
    }

    wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
                  wxT("process should have terminated") );

   
    ::SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);

    return 0;
}



long wxExecuteHidden(const wxString& cmd, int flags, wxProcess *handler) {
    wxCHECK_MSG( !cmd.empty(), 0, wxT("empty command in wxExecute") );

#if wxUSE_THREADS
   
   
   
    wxASSERT_MSG( wxThread::IsMain(),
                    _T("wxExecute() can be called only from the main thread") );
#endif

    wxString command;

#if wxUSE_IPC
#endif
    {
       
        command = cmd;
    }

   
    BOOL redirect = FALSE;

   
    STARTUPINFO si;
    wxZeroMemory(si);
    si.cb = sizeof(si);

//DM ADDED CODE HERE
   
   
   
    if ( !(flags & wxEXEC_NOHIDE) )
    {
        si.dwFlags |= STARTF_USESHOWWINDOW;
        si.wShowWindow = SW_HIDE;
    }

    PROCESS_INFORMATION pi;
    DWORD dwFlags = CREATE_SUSPENDED;

#ifndef __WXWINCE__
    dwFlags |= CREATE_DEFAULT_ERROR_MODE ;
#else
   
    wxString moduleName = command.BeforeFirst(wxT(' '));
    wxString arguments = command.AfterFirst(wxT(' '));
#endif

    bool ok = ::CreateProcess
                (
                   
                   
#ifdef __WXWINCE__
                 (wxChar *)
                 moduleName.c_str(),
                 (wxChar *)
                 arguments.c_str(), 
#else
                 NULL,              
                 (wxChar *)
                 command.c_str(),   
#endif
                 NULL,              
                 NULL,              
                 redirect,          
                 dwFlags,           
                 NULL,              
                 NULL,              
                 &si,               
                 &pi                
                ) != 0;

    if ( !ok )
    {

        wxLogSysError(_("Execution of command '%s' failed"), command.c_str());

        return flags & wxEXEC_SYNC ? -1 : 0;
    }


   
   
    HWND hwnd = wxCreateHiddenWindow
                (
                    &gs_classForHiddenWindow2,
                    wxMSWEXEC_WNDCLASSNAME2,
                    (WNDPROC)wxExecuteWindowCbk2
                );

    wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );

   
    wxExecuteData2 *data = new wxExecuteData2;
    data->hProcess    = pi.hProcess;
    data->dwProcessId = pi.dwProcessId;
    data->hWnd        = hwnd;
    data->state       = (flags & wxEXEC_SYNC) != 0;
    if ( flags & wxEXEC_SYNC )
    {
       
       
        data->handler = NULL;
    }
    else
    {
       
        data->handler = handler;
    }

    DWORD tid;
    HANDLE hThread = ::CreateThread(NULL,
                                    0,
                                    wxExecuteThread2,
                                    (void *)data,
                                    0,
                                    &tid);

   
   
    if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
    {
       
        wxLogLastError(wxT("ResumeThread in wxExecute"));
    }

   
    if ( !::CloseHandle(pi.hThread) )
        wxLogLastError(wxT("CloseHandle(hThread)"));

    if ( !hThread )
    {
        wxLogLastError(wxT("CreateThread in wxExecute"));

        DestroyWindow(hwnd);
        delete data;

       
        return pi.dwProcessId;
    }

    ::CloseHandle(hThread);

#if wxUSE_IPC && !defined(__WXWINCE__)
#endif

    if ( !(flags & wxEXEC_SYNC) )
    {
       

       
        return pi.dwProcessId;
    }

    wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
    wxCHECK_MSG( traits, -1, _T("no wxAppTraits in wxExecute()?") );

    void *cookie = NULL;
    if ( !(flags & wxEXEC_NODISABLE) )
    {
       
        cookie = traits->BeforeChildWaitLoop();
    }

   
    while ( data->state )
    {
       
       
        ::Sleep(50);

       
        traits->AlwaysYield();
    }

    if ( !(flags & wxEXEC_NODISABLE) )
    {
       
        traits->AfterChildWaitLoop(cookie);
    }

    DWORD dwExitCode = data->dwExitCode;
    delete data;

   
    return dwExitCode;
}

long wxExecuteHidden(wxChar **argv, int flags, wxProcess *handler) {
    wxString command;

    for ( ;; )
    {
        command += *argv++;
        if ( !*argv )
            break;

        command += _T(' ');
    }

    return wxExecuteHidden(command, flags, handler);
}

#endif 
